package com.xaicode.learn.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * file -> channel -> file.copy
 *
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 1:36
 */
@Slf4j
public class NIOFileChannel03 {

    private static final String FILE_PATH = "logs" + File.separator;
    private static final String FILE_IN = FILE_PATH + "NIOFileChannel01.txt";
    private static final String FILE_OUT = FILE_PATH + "NIOFileChannel01.txt.copy";

    public static void main(String[] args) {

        try (
                // create file input stream
                FileInputStream inputStream = new FileInputStream(FILE_IN);
                // create file output stream
                FileOutputStream outputStream = new FileOutputStream(FILE_OUT)
        ) {
            final FileChannel inputFileChannel = inputStream.getChannel();
            final FileChannel outputFileChannel = outputStream.getChannel();

            final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            while (true) {

                /*
                    public final Buffer clear() {
                        position = 0;
                        limit = capacity;
                        mark = -1;
                        return this;
                    }
                 */
                byteBuffer.clear();

                // input channel read file
                final int read = inputFileChannel.read(byteBuffer);
                // read complete
                if (read == -1) {
                    break;
                }
                // buffer to output channel
                byteBuffer.flip();
                outputFileChannel.write(byteBuffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
